package com.example.mqttclient;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.mqttclient.mqtt.MqttService;

import org.eclipse.paho.client.mqttv3.MqttException;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements MqttService.MqttEventCallBack {

    private TextView connectState;
    private MqttService.MqttBinder mqttBinder;
    private String TAG = "MainActivity";
    private SharedPreferences sharedPreferences;
    private Button[] themeButtons;
    private int[] themeColors = {
            R.color.theme_red,
            R.color.theme_blue,
            R.color.theme_green,
            R.color.theme_yellow,
            R.color.theme_purple
    };
    private int[] themeBgColors = {
            R.color.theme_bg_red,
            R.color.theme_bg_blue,
            R.color.theme_bg_green,
            R.color.theme_bg_yellow,
            R.color.theme_bg_purple
    };
    private String[] themeTags = {"red", "blue", "green", "yellow", "purple"};

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mqttBinder = (MqttService.MqttBinder) iBinder;
            mqttBinder.setMqttEventCallBack(MainActivity.this);
            if (mqttBinder.isConnected()) {
                connectState.setText("已连接");
                subscribeTopics();
            } else {
                connectState.setText("未连接");
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 必须在setContentView之前应用主题
        sharedPreferences = getSharedPreferences("AppSettings", Context.MODE_PRIVATE);
        String savedTheme = sharedPreferences.getString("theme", "red");
        applyTheme(savedTheme);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        connectState = findViewById(R.id.connect_state);

        Intent mqttServiceIntent = new Intent(this, MqttService.class);
        bindService(mqttServiceIntent, connection, Context.BIND_AUTO_CREATE);

        findViewById(R.id.settings_btn).setOnClickListener((view) -> {
            Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
            startActivity(intent);
        });

        findViewById(R.id.pubsub_test_btn).setOnClickListener((view) -> {
            Intent intent = new Intent(MainActivity.this, PubSubTestActivity.class);
            startActivity(intent);
        });

        findViewById(R.id.dev_demo_btn).setOnClickListener((view) -> {
            Intent intent = new Intent(MainActivity.this, DevicesDemoActivity.class);
            startActivity(intent);
        });

        // 初始化主题选择按钮
        initThemeButtons();
    }

    private void initThemeButtons() {
        themeButtons = new Button[5];
        themeButtons[0] = findViewById(R.id.theme_red);
        themeButtons[1] = findViewById(R.id.theme_blue);
        themeButtons[2] = findViewById(R.id.theme_green);
        themeButtons[3] = findViewById(R.id.theme_yellow);
        themeButtons[4] = findViewById(R.id.theme_purple);

        // 设置当前选中的主题
        String savedTheme = sharedPreferences.getString("theme", "red");
        for (int i = 0; i < themeButtons.length; i++) {
            if (themeTags[i].equals(savedTheme)) {
                themeButtons[i].setBackgroundResource(R.drawable.theme_button_selected);
            } else {
                themeButtons[i].setBackgroundResource(R.drawable.theme_button);
            }

            // 设置点击事件
            final int index = i;
            themeButtons[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    selectTheme(themeTags[index]);
                }
            });
        }
    }

    private void selectTheme(String theme) {
        // 保存选择的主题
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("theme", theme);
        editor.apply();

        // 应用新主题
        applyTheme(theme);

        // 更新按钮状态
        for (int i = 0; i < themeButtons.length; i++) {
            if (themeTags[i].equals(theme)) {
                themeButtons[i].setBackgroundResource(R.drawable.theme_button_selected);
            } else {
                themeButtons[i].setBackgroundResource(R.drawable.theme_button);
            }
        }

        // 刷新界面
        recreate();
    }

    private void applyTheme(String theme) {
        // 获取主题颜色索引
        int themeIndex = 0;
        for (int i = 0; i < themeTags.length; i++) {
            if (themeTags[i].equals(theme)) {
                themeIndex = i;
                break;
            }
        }

        // 更新主题颜色资源
        int colorResId = themeColors[themeIndex];
        int bgColorResId = themeBgColors[themeIndex];

        // 保存主题资源ID
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("theme_color", colorResId);
        editor.putInt("theme_background", bgColorResId);
        editor.apply();
    }

    void subscribeTopics() {
        try {
            mqttBinder.subscribe("/test");
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    void unSubscribeTopics() {
        try {
            mqttBinder.unsubscribe("/test");
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onConnectSuccess() {
        subscribeTopics();
        connectState.setText("已连接");
    }

    @Override
    public void onConnectError(String error) {
        Log.d(TAG, "onConnectError: " + error);
        connectState.setText("未连接");
    }

    @Override
    public void onDeliveryComplete() {
        Log.d(TAG, "publish ok");
    }

    @Override
    public void onMqttMessage(String topic, String message) {
        // 可在此处添加接收到消息后的具体处理逻辑
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (mqttBinder.isConnected()) {
            connectState.setText("已连接");
            subscribeTopics();
        } else {
            connectState.setText("未连接");
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        unSubscribeTopics();
    }

    @Override
    protected void onDestroy() {
        unbindService(connection);
        super.onDestroy();
    }
}